package com.smart.community.region.service.impl;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.IPropertyCompanyCommunityFeign;
import com.smart.community.region.dto.ZoneDrawingSaveDTO;
import com.smart.community.region.dto.ZoneSaveRequest;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Zone;
import com.smart.community.region.entity.ZoneDrawing;
import com.smart.community.region.service.IBuildingService;
import com.smart.community.region.service.ICommunityService;
import com.smart.community.region.service.IZoneDrawingService;
import com.smart.community.region.service.IZoneManagementService;
import com.smart.community.region.service.IZoneService;
import com.smart.community.region.vo.CommunityEntryStateVO;
import com.smart.community.region.vo.ZoneManagementInitialDataVO;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 分区管理服务实现类
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */
@Service
@Slf4j
public class ZoneManagementServiceImpl implements IZoneManagementService {

    @Autowired
    private IZoneService zoneService;

    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private IZoneDrawingService zoneDrawingService;

    @Autowired
    private IPropertyCompanyCommunityFeign propertyCompanyCommunityFeign;

    @Override
    public CommunityEntryStateVO determineCommunityEntryState(Long communityId) {
        log.info("判断社区进入状态，社区ID: {}", communityId);
        
        // 直接查询分区表，检查是否有分区数据
        LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Zone::getCommunityId, communityId)
                   .eq(Zone::getDeleted, 0);
        List<Zone> zones = zoneService.list(queryWrapper);
        
        boolean hasExistingZones = !zones.isEmpty();
        
        // 获取最后修改时间
        String lastModifiedTime = null;
        if (hasExistingZones && !zones.isEmpty()) {
            Zone latestZone = zones.stream()
                .max(Comparator.comparing(Zone::getUpdateTime))
                .orElse(null);
            if (latestZone != null) {
                lastModifiedTime = latestZone.getUpdateTime().toString();
            }
        }
        
        // 判断是否初次进入
        boolean isFirstEntry = !hasExistingZones;
        
        CommunityEntryStateVO state = new CommunityEntryStateVO();
        state.setFirstEntry(isFirstEntry);
        state.setHasExistingZones(hasExistingZones);
        state.setZoneCount(zones.size());
        state.setLastModifiedTime(lastModifiedTime);
        
        return state;
    }

    @Override
    public ZoneManagementInitialDataVO getInitialData(Long communityId) {
        log.info("获取分区管理初始数据，社区ID: {}", communityId);
        
        ZoneManagementInitialDataVO data = new ZoneManagementInitialDataVO();
        
        // 获取社区信息
        data.setCommunityInfo(communityService.getById(communityId));
        
        // 获取楼栋列表
        try {
            List<Building> buildings = buildingService.getBuildingsByCommunity(communityId);
            data.setBuildingList(new java.util.ArrayList<>(buildings));
        } catch (Exception e) {
            log.error("获取楼栋列表失败", e);
            data.setBuildingList(new java.util.ArrayList<>());
        }
        
        // 获取分区列表
        LambdaQueryWrapper<Zone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Zone::getCommunityId, communityId)
                   .eq(Zone::getDeleted, 0)
                   .orderByDesc(Zone::getSortOrder);
        List<Zone> zones = zoneService.list(queryWrapper);
        data.setZoneList(new java.util.ArrayList<>(zones));
        
        // 获取绘图数据（无论是否有分区数据都尝试加载）
        try {
            LambdaQueryWrapper<ZoneDrawing> drawingQueryWrapper = new LambdaQueryWrapper<>();
            drawingQueryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                             .eq(ZoneDrawing::getIsCurrent, 1)
                             .eq(ZoneDrawing::getDeleted, 0);
            ZoneDrawing drawing = zoneDrawingService.getOne(drawingQueryWrapper);
            if (drawing != null) {
                data.setDrawingData(drawing);
                log.info("绘图数据加载成功，社区ID: {}", communityId);
            } else {
                log.info("未找到绘图数据，社区ID: {}", communityId);
            }
        } catch (Exception e) {
            log.error("获取绘图数据失败，社区ID: {}", communityId, e);
        }
        
        return data;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String saveZoneData(ZoneSaveRequest request) {
        log.info("保存分区管理数据，社区ID: {}", request.getCommunityId());
        
        // TODO: 实现分区管理数据的保存逻辑
        // 这里需要根据具体的业务需求实现
        
        return "保存成功";
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String saveDrawingData(ZoneDrawingSaveDTO request) {
        log.info("保存绘图数据，社区ID: {}", request.getCommunityId());
        
        // 获取物业公司ID：优先使用前端传递的，如果没有则根据社区ID获取
        Long propertyCompanyId = request.getPropertyCompanyId();
        if (propertyCompanyId == null) {
            propertyCompanyId = getPropertyCompanyIdByCommunityId(request.getCommunityId());
        }
        
        // 创建新的绘图数据记录
        ZoneDrawing drawing = new ZoneDrawing();
        drawing.setCommunityId(request.getCommunityId());
        drawing.setPropertyCompanyId(propertyCompanyId);
        drawing.setDrawingData(com.alibaba.fastjson.JSON.toJSONString(request));
        drawing.setCanvasWidth(800);
        drawing.setCanvasHeight(600);
        drawing.setZoomLevel(new java.math.BigDecimal("1.0"));
        drawing.setVersion(1);
        drawing.setIsCurrent(1);
        // 设置创建用户信息，遵循规范
        Long currentUserId = SecurityUtils.getCurrentUserId();
        drawing.setCreateBy(currentUserId);
        drawing.setUpdateBy(currentUserId);
        LocalDateTime now = LocalDateTime.now();
        drawing.setCreateTime(now);
        drawing.setUpdateTime(now);
        
        boolean success = zoneDrawingService.save(drawing);
        if (success) {
            return "保存成功";
        } else {
            throw new RuntimeException("保存绘图数据失败");
        }
    }

    /**
     * 根据社区ID获取物业公司ID
     * 
     * @param communityId 社区ID
     * @return 物业公司ID，如果没有关联则返回null
     */
    private Long getPropertyCompanyIdByCommunityId(Long communityId) {
        try {
            // 通过Feign客户端调用物业服务获取物业公司ID
            Long propertyCompanyId = propertyCompanyCommunityFeign.getPropertyCompanyIdByCommunityId(communityId);
            if (propertyCompanyId != null) {
                log.info("根据社区ID获取物业公司ID成功，社区ID: {}，物业公司ID: {}", communityId, propertyCompanyId);
                return propertyCompanyId;
            } else {
                log.warn("社区ID: {} 未关联任何物业公司", communityId);
                return null;
            }
        } catch (Exception e) {
            log.error("根据社区ID获取物业公司ID失败，社区ID: {}", communityId, e);
            return null;
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String updateDrawingData(Long id, ZoneDrawingSaveDTO request) {
        log.info("更新绘图数据，ID: {}, 社区ID: {}", id, request.getCommunityId());
        
        // 验证ID参数
        if (id == null) {
            throw new RuntimeException("绘图数据ID不能为空");
        }
        
        // 获取现有绘图数据
        ZoneDrawing existingDrawing = zoneDrawingService.getById(id);
        if (existingDrawing == null) {
            throw new RuntimeException("绘图数据不存在，ID: " + id);
        }
        
        // 获取物业公司ID：优先使用前端传递的，如果没有则根据社区ID获取
        Long propertyCompanyId = request.getPropertyCompanyId();
        if (propertyCompanyId == null) {
            propertyCompanyId = getPropertyCompanyIdByCommunityId(request.getCommunityId());
            log.info("前端未传递物业公司ID，根据社区ID获取物业公司ID，社区ID: {}，物业公司ID: {}", 
                    request.getCommunityId(), propertyCompanyId);
        }
        
        // 更新绘图数据
        existingDrawing.setDrawingData(com.alibaba.fastjson.JSON.toJSONString(request));
        existingDrawing.setPropertyCompanyId(propertyCompanyId); // 确保物业公司ID正确设置
        existingDrawing.setUpdateTime(java.time.LocalDateTime.now());
        // 设置更新用户信息，遵循规范
        existingDrawing.setUpdateBy(SecurityUtils.getCurrentUserId());
        
        boolean success = zoneDrawingService.updateById(existingDrawing);
        if (success) {
            return "更新成功";
        } else {
            throw new RuntimeException("更新绘图数据失败");
        }
    }

    @Override
    public Object getCommunityDrawingData(Long communityId) {
        log.info("获取社区绘图数据，社区ID: {}", communityId);
        
        LambdaQueryWrapper<ZoneDrawing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZoneDrawing::getCommunityId, communityId)
                   .eq(ZoneDrawing::getIsCurrent, 1)
                   .eq(ZoneDrawing::getDeleted, 0);
        ZoneDrawing drawing = zoneDrawingService.getOne(queryWrapper);
        
        if (drawing != null) {
            // 解析绘图数据JSON并添加ID信息
            Object drawingData = com.alibaba.fastjson.JSON.parse(drawing.getDrawingData());
            
            // 如果返回的是Map类型，添加ID信息
            if (drawingData instanceof java.util.Map) {
                @SuppressWarnings("unchecked")
                java.util.Map<String, Object> dataMap = (java.util.Map<String, Object>) drawingData;
                dataMap.put("id", drawing.getId());
                dataMap.put("drawingId", drawing.getId()); // 添加drawingId字段作为备用
                return dataMap;
            }
            
            // 如果返回的是其他类型，创建一个包含ID的新Map
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("id", drawing.getId());
            result.put("drawingId", drawing.getId());
            result.put("drawingData", drawingData);
            return result;
        }
        
        return null;
    }
}

